#include "APP_Control_Motor.h"
#include "usart.h"
int16_t joystick_bias[1] = {0};

// 设置电机结构体初始化状态
Motor_Struct motor_485_stc = {&htim4, TIM_CHANNEL_4, 0};
TW_51_enum TW_motor_status = MOTOR_STOP;
extern uint8_t CO_Flag;
void APP_Motor_SetSpeed(TW_51_enum motor_status, Motor_Struct *motor)
{
    //     motor_status = MOTOR_START;
    //     motor->speed = 100;
    //    Motor_485_SetSpeed(motor_status, 100);
    if (CO_Flag == 1) {
        // 让电机转动
        HAL_UART_Transmit(&huart3, "4", 1, 1000);
        motor_status = MOTOR_START;       
    }

    switch (motor_status) {
        case MOTOR_STOP:
            // 电机停止
            // printf("stop----------------\r\n");
            motor->speed = 0;
            break;
        case MOTOR_START:
            // 电机启动,默认正向匀速转动
            //  先写死，待优化
            // printf("start----------------------\r\n");
            motor->speed = 50;
            break;
        case MOTOR_REVERSE:
            // 电机反转
            // printf("reverse--------------------\r\n");
            motor->speed -= 50;
            if (motor->speed < -850) {
                motor->speed = -850;
            }
            break;
        case MOTOR_FORWARD:
            // 电机前进
            // printf("forward-------------------\r\n");
            motor->speed += 50;
            if (motor->speed > 850) {
                motor->speed = 850;
            }
            break;
        default:
            break;
    }

    Motor_485_SetSpeed(motor_status, (uint16_t)motor_485_stc.speed);
}

void TW_51_Motor_Control(void)
{
}

// 扫描按键任务

void APP_Key_Scan_Task(Remote_key *remote_key)
{
    //  OLED_ShowString(3, 12, "start");
    printf("%d", remote_key->speed);
    // 扫描按键
    Int_key_scan(remote_key);
    // 根据采集到ADC的值判断按键(待处理)
    if (remote_key->speed > 3701 && remote_key->speed < 3710) {
        // 启动电机
        TW_motor_status = MOTOR_START;
        HAL_UART_Transmit(&huart3, "1", 1, 1000);
        // motor_485_stc.speed = 50;
        APP_Motor_SetSpeed(TW_motor_status, &motor_485_stc);
    } else if (remote_key->speed > 3881 && remote_key->speed < 3890) {

        TW_motor_status = MOTOR_FORWARD;
        HAL_UART_Transmit(&huart3, "2", 1, 1000);
        // motor_485_stc.speed += 50;
        APP_Motor_SetSpeed(TW_motor_status, &motor_485_stc);
    } else if (remote_key->speed <= 10) {
        // 关闭电机

        // 通过串口向天问51发送当前状态
        TW_motor_status = MOTOR_STOP;
        HAL_UART_Transmit(&huart3, "0", 1, 1000);

        // motor_485_stc.speed = 0;
        APP_Motor_SetSpeed(TW_motor_status, &motor_485_stc);
    } else if (remote_key->speed < 3951 && remote_key->speed > 3944) {
        // 反向加速转动
        TW_motor_status = MOTOR_REVERSE;
        HAL_UART_Transmit(&huart3, "3", 1, 1000);
        // motor_485_stc.speed -= 50;
        APP_Motor_SetSpeed(TW_motor_status, &motor_485_stc);
    }
}
